<template>
  <div style="margin-top: 10px;">
    <!--  搜索条件  -->
    <div>
      <el-select v-model="searchForm.appId" style="margin-right: 10px; width: 130px;"
                 @change="onSelectedApp($event)"
                 filterable clearable placeholder="-请选择应用-">
        <el-option
            v-for="item in appList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
        </el-option>
      </el-select>

      <el-select v-model="searchForm.userId" style="margin-right: 10px; width: 130px;"
                 @change="onSelectedUser($event)"
                 filterable clearable placeholder="-请选择负责人-">
        <el-option
            v-for="item in userList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
        </el-option>
      </el-select>

      <el-select v-model="searchForm.status" style="margin-right: 10px; width: 130px;"
                 @change="onSelectedStatus($event)"
                 filterable clearable placeholder="-请选择状态-">
        <el-option
            v-for="item in statusList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
        </el-option>
      </el-select>

      <!-- 输入框，可按此方式根据实际情况动态修改或扩增 -->
      <el-input placeholder="请输入接口名称/路径搜索" prefix-icon="el-icon-search"
                clearable
                @clear="initDataList"
                style="width: 250px;margin-right: 10px" v-model="searchForm.name"
                @keydown.enter.native="initDataList">
      </el-input>

      <el-button type="primary" icon="el-icon-search" @click="search">
        查询
      </el-button>

      <el-select v-model="env" style="margin-left: 10px; float: right; width: 100px;"
                 @change="onSelectedEnv($event)"
                 filterable>
        <el-option
            v-for="item in envList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
        </el-option>
      </el-select>
      <el-button type="primary" icon="el-icon-plus" @click="add" style="float: right">
        新增
      </el-button>
      <el-button icon="el-icon-refresh" style="display: inline-flex;margin-right: 8px;float: right" type="primary"
                 @click="flushTable"></el-button>
    </div>

    <div style="margin-top: 10px; height: auto;">
      <el-table :data="dataList" border stripe size="mini" height="500" style="width: 100%" :header-cell-style="{background:'#f5f7fa',color:'#606266'}">
        <el-table-column type="index" label="序号" fixed align="center" width="50px;"></el-table-column>
        <!-- <el-table-column type="selection" align="left" width="55"></el-table-column> -->
        <el-table-column prop="id" label="主键ID" align="left" v-if="idShow"></el-table-column>

        <el-table-column prop="appId" label="所属应用ID" width="50px;" align="left" :show-overflow-tooltip="true" v-if="false">
          <el-tag slot-scope="scope" @click="handleCopy(scope.row.appId)">{{ scope.row.appId }}</el-tag>
        </el-table-column>

        <el-table-column prop="appName" label="所属应用" fixed width="150px;" align="left" :show-overflow-tooltip="true">
          <el-tag slot-scope="scope" @click="handleCopy(scope.row.appName)">{{ scope.row.appName }}</el-tag>
        </el-table-column>

        <el-table-column prop="name" label="接口名称" width="150px;" :show-overflow-tooltip="true">
          <el-tag slot-scope="scope" @click="handleCopy(scope.row.name)">{{ scope.row.name }}</el-tag>
        </el-table-column>

        <el-table-column prop="status" label="接口状态" width="100px;" align="center" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <el-tag v-show="scope.row.status === 1" type="success">正常</el-tag>
            <el-tag v-show="scope.row.status === 0" type="danger">异常</el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="path" label="接口路径" width="200px;" :show-overflow-tooltip="true">
          <el-tag slot-scope="scope" @click="handleCopy(scope.row.path)">{{ scope.row.path }}</el-tag>
        </el-table-column>

        <el-table-column prop="method" label="请求类型" width="100px;" :show-overflow-tooltip="true">
          <el-tag slot-scope="scope" @click="handleCopy(scope.row.method)">{{ scope.row.method }}</el-tag>
        </el-table-column>

        <el-table-column prop="header" label="请求头" width="150px;" :show-overflow-tooltip="true">
          <el-tag slot-scope="scope" @click="handleCopy(scope.row.header)">{{ scope.row.header }}</el-tag>
        </el-table-column>

        <el-table-column prop="params" label="请求参数" width="200px;" :show-overflow-tooltip="true">
          <el-tag slot-scope="scope" @click="handleCopy(scope.row.params)">{{ scope.row.params }}</el-tag>
        </el-table-column>

        <el-table-column prop="userId" label="接口负责人ID" width="20px;" :show-overflow-tooltip="true" v-if="false">
          <el-tag slot-scope="scope" @click="handleCopy(scope.row.userId)">{{ scope.row.userId }}</el-tag>
        </el-table-column>
        <el-table-column prop="userName" label="接口负责人" width="100px;" :show-overflow-tooltip="true">
          <el-tag slot-scope="scope" @click="handleCopy(scope.row.userName)">{{ scope.row.userName }}</el-tag>
        </el-table-column>

        <!-- 创建时间、更新时间必备 -->
        <el-table-column prop="createTime" label="创建时间" width="150px;" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="150px;" align="center" :show-overflow-tooltip="true"></el-table-column>

        <!-- 操作必备 -->
        <el-table-column label="操作" align="center" fixed="right" width="350px;">
          <template slot-scope="scope">
            <el-button @click="interfaceTest(scope.row)" class="el-icon-aim" type="success">测试</el-button>
            <el-button @click="view(scope.row)" class="el-icon-view" type="primary">查看</el-button>
            <el-button @click="edit(scope.row)" class="el-icon-edit" type="primary">编辑</el-button>
            <el-button @click="del(scope.row)" class="el-icon-delete" type="danger">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div style="display: flex;justify-content: flex-end">
      <el-pagination
          background
          :current-page.sync="searchForm.pageNum"
          @size-change="pageSizeChange"
          @current-change="pageNumChange"
          layout="sizes, prev, pager, next, jumper, ->, total, slot"
          :total="total">
      </el-pagination>
    </div>

    <!-- 查看/新增/编辑 对话框 -->
    <div>
      <el-dialog v-dialogDrag
                 :modal-append-to-body="false"
                 :title="operateTitle"
                 :visible.sync="saveDialogVisible"
                 width="45%"
                 top="20vh">

        <el-form :model="saveForm" :rules="saveFormRules" ref="saveFormRef" label-width="100px" label-position="left">
          <el-form-item label="主键ID" prop="id" v-show="false">
            <el-input class="formItem" v-model="saveForm.id" :disabled="viewMode"></el-input>
          </el-form-item>

          <el-form-item label="所属应用" prop="appId">
            <el-select class="formItem" v-model="saveForm.appId"
                       @change="onFormSelectedApp($event)" :disabled="viewMode"
                       filterable placeholder="-请选择应用-">
              <el-option
                  v-for="item in appList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="接口名称" prop="name">
            <el-input class="formItem" v-model="saveForm.name" :disabled="viewMode"></el-input>
          </el-form-item>

          <el-form-item label="接口路径" prop="path">
            <el-input class="formItem" type="textarea" autosize v-model="saveForm.path" :disabled="viewMode"></el-input>
          </el-form-item>

          <el-form-item label="请求类型" prop="method">
            <el-select class="formItem" v-model="saveForm.method"
                       @change="onFormSelectedMethod($event)" :disabled="viewMode"
                       filterable placeholder="-请选择请求类型-">
              <el-option
                  v-for="item in methodList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="请求头" prop="header">
            <el-input class="formItem" type="textarea" :rows="5" v-model="saveForm.header" :disabled="viewMode"></el-input>
          </el-form-item>

          <el-form-item label="请求参数" prop="params">
            <el-input class="formItem" type="textarea" :rows="5" v-model="saveForm.params" :disabled="viewMode"></el-input>
          </el-form-item>

          <el-form-item label="负责人" prop="userId">
            <el-select class="formItem" v-model="saveForm.userId"
                       @change="onFormSelectedUser($event)" :disabled="viewMode"
                       filterable placeholder="-请选择负责人-">
              <el-option
                  v-for="item in userList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="formReset" v-if="resetVisible">重置</el-button>
          <el-button type="primary" @click="saveCancel">取消</el-button>
          <el-button type="primary" @click="save" v-if="!viewMode">确定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {Message} from "element-ui";
import {deepClone, unique} from "@/utils/tool";
import '@/utils/dialog'

export default {
  name: "InterfaceManage",
  data() {
    return {
      userList: [],
      appList: [],
      envList: [{id: 'dev', name: '开发环境'}, {id: 'test', name: '测试环境'}, {id: 'local', name: '本地环境'}],
      methodList: [{id:'GET', name: 'GET'}, {id:'POST', name: 'POST'}, ],
      statusList: [{id:'0', name: '异常'}, {id:'1', name: '正常'}],
      // 列表数据
      dataList: [],
      // 列表数据总量
      total: 0,
      // 列表数据的ID是否显示(默认不显示)
      idShow: false,
      env: 'dev',
      // 【getPageInfo】接口需要的字段封装对象
      searchForm: {
        appId: '',
        userId: '',
        name: '',
        status: '',
        // 分页查询条件
        pageNum: 1,
        pageSize: 10,
        // 可根据【getPageInfo】接口动态增加字段
      },

      // 查看、新增、编辑对话框标题
      operateTitle: '标题',
      // 查看、新增、编辑对话框是否可见
      saveDialogVisible: false,
      // 查看、新增、编辑对话框的重置按钮是否可见
      resetVisible: false,
      // 是否是查看模式
      viewMode: false,

      // 【save】接口需要的字段封装对象
      saveForm: {
        id: '',
        appId: '',
        appName: '',
        name: '',
        method: 'GET',
        methodName: '',
        path: '',
        header: '',
        params: '',
        userId: '',
        userName: '',
      },
      // 【save】接口参数用户输入校验
      saveFormRules: {
        appId: [
          {required: true, message: '请选择应用', trigger: 'blur'},
        ],
        name: [
          {required: true, message: '请输入接口名称', trigger: 'blur'},
          {min: 1, max: 255, message: '长度在 1 到 255 个字符', trigger: 'blur'}
        ],
        method: [
          {required: true, message: '请选择请求类型', trigger: 'blur'},
          {min: 1, max: 8, message: '长度在 1 到 8 个字符', trigger: 'blur'},
        ],
        path: [
          {required: true, message: '请输入接口路径', trigger: 'blur'},
          {min: 1, max: 255, message: '长度在 1 到 255 个字符', trigger: 'blur'},
        ],
        header: [
          {required: false, message: '请输入请求头', trigger: 'blur'},
          {min: 1, max: 255, message: '长度在 1 到 255 个字符', trigger: 'blur'},
        ],
        params: [
          {required: false, message: '请输入请求参数', trigger: 'blur'},
          {min: 1, max: 2048, message: '长度在 1 到 2048 个字符', trigger: 'blur'},
        ],
        userId: [
          {required: true, message: '请选择接口负责人', trigger: 'blur'},
        ],
      },
    }
  },

  // 初始化组件时加载数据
  mounted() {
    // 加载表格数据
    this.initDataList();
    // 加载下拉选框数据
    this.initUserList();
    this.initAppList();
  },

  methods: {
    // 调用后端【getPageInfo】接口获取表格数据
    initDataList() {
      this.getRequest("/interfaceManage/getPageInfo", this.searchForm).then(resp => {
        this.loading = true;
        if (resp && resp.status === 200) {
          // resp.data.forEach(function(obj) {
          //   departmentList.push({'value': obj.id, 'label': obj.name});
          // });
          this.dataList = resp.data.list;
          this.total = resp.data.total;
          this.loading = false;
        }
      })
    },

    // 调用后端【getList】接口获取集合数据给下拉选框赋值
    initUserList() {
      this.getRequest("/sysUser/getList").then(resp => {
        this.loading = true;
        if (resp && resp.status === 200) {
          this.userList = resp.data;
          // 去重处理(按需设定，可将需要去重的值设置给id属性)
          const tempList = deepClone(this.userList);
          let list = tempList.map((item,index) => {
            return {
              index: index,
              id: item.id,
              name: item.name,
            };
          });
          // 根据id去重
          this.userList = unique(list);
        }
      })
    },

    initAppList() {
      this.getRequest("/appManage/getList").then(resp => {
        this.loading = true;
        if (resp && resp.status === 200) {
          this.appList = resp.data;
          // 去重处理(按需设定，可将需要去重的值设置给id属性)
          const tempList = deepClone(this.appList);
          let list = tempList.map((item,index) => {
            return {
              index: index,
              id: item.id,
              name: item.appName,
            };
          });
          // 根据id去重
          this.appList = unique(list);
        }
      })
    },

    // 点击搜索搜索
    search() {
      this.initDataList();
    },

    flushTable() {
      this.initDataList();
      Message.success("刷新成功");
    },

    // 页码切换
    pageNumChange(page) {
      this.searchForm.pageNum = page;
      this.initDataList();
    },
    // 每页数量切换
    pageSizeChange(size) {
      this.searchForm.pageSize = size;
      this.searchForm.pageNum = 1;
      this.initDataList();
    },

    // 点击新增
    add() {
      if (this.$refs['saveFormRef'] !== undefined) {
        this.$refs['saveFormRef'].resetFields();
      }
      this.operateTitle = '新增数据';
      this.viewMode = false;
      this.resetVisible = true;
      this.saveDialogVisible = true;
    },
    // 点击查看
    view(row) {
      this.operateTitle = "查看数据";
      this.saveForm = deepClone(row);
      this.viewMode = true;
      this.resetVisible = false;
      this.saveDialogVisible = true;
    },
    // 点击编辑
    edit(row) {
      this.operateTitle = '编辑数据';
      this.saveForm = deepClone(row);
      this.viewMode = false;
      this.resetVisible = false;
      this.saveDialogVisible = true;
    },
    // 点击删除
    del(row) {
      this.$confirm('删除后无法恢复！！！确认删除?')
          .then(() => {
            this.putRequest('/interfaceManage/delete', row).then(resp => {
              if (resp && resp.status === 200) {
                this.initDataList();
                Message.success("删除成功");
              }
            })
          }).catch(ex => {
        console.error("删除异常：" + ex)
      });
    },

    interfaceTest(row) {
      row.env = this.env;
      this.postRequest('/interfaceManage/testInterface', row).then((resp => {
        if (resp && resp.status === 200) {
          this.initDataList();
          Message.success("测试成功");
        }
      }));
    },

    // 新增、编辑对话框表单重置
    formReset() {
      if (this.$refs['saveFormRef'] !== undefined) {
        this.$refs['saveFormRef'].resetFields();
      }
      Message.success("重置成功")
    },
    // 新增、编辑对话框表单取消
    saveCancel() {
      this.saveDialogVisible = false;
    },
    // 新增、编辑对话框表单确定
    save() {
      const id = this.saveForm.id;
      this.$refs['saveFormRef'].validate((valid) => {
        if (valid && !id) {
          // 如果id不存在，则新增数据
          this.postRequest('/interfaceManage/insert', this.saveForm).then((resp => {
            if (resp && resp.status === 200) {
              this.initDataList();
              this.saveDialogVisible = false;
              Message.success("新增成功");
            }
          }));
        } else if (id) {
          // 如果id存在，则更新数据
          this.postRequest('/interfaceManage/update', this.saveForm).then((resp => {
            if (resp && resp.status === 200) {
              this.initDataList();
              this.saveDialogVisible = false;
              Message.success("更新成功");
            }
          }));
        } else {
          return false;
        }
      })
    },
    onSelectedApp(eventId) {
      if (!eventId) {
        this.searchForm.appId = '';
        this.searchForm.appName = '';
        this.initDataList();
        return false;
      }
      let obj = this.appList.find(item => {
        return item.id === eventId;
      });
      this.searchForm.appId = eventId;
      this.searchForm.appName = obj.name;
      this.initDataList();
    },
    onSelectedUser(eventId) {
      if (!eventId) {
        this.searchForm.userId = '';
        this.searchForm.userName = '';
        this.initDataList();
        return;
      }
      let obj = this.userList.find(item => {
        return item.id === eventId;
      });
      this.searchForm.userId = eventId;
      this.searchForm.userName = obj.name;
      this.initDataList();
    },
    onSelectedStatus(eventId) {
      if (!eventId) {
        this.searchForm.status = '';
        this.initDataList();
        return;
      }
      this.searchForm.status = eventId;
      this.initDataList();
    },

    onSelectedEnv(envId) {
      if (!envId) {
        this.env = '';
        return;
      }
      this.env = envId;
    },

    onFormSelectedApp(eventId) {
      if (!eventId) {
        this.saveForm.appId = '';
        this.saveForm.appName = '';
        return false;
      }
      let obj = this.appList.find(item => {
        return item.id === eventId;
      });
      this.saveForm.appId = eventId;
      this.saveForm.appName = obj.name;
    },

    onFormSelectedMethod(eventId) {
      if (!eventId) {
        this.saveForm.method = '';
        this.saveForm.methodName = '';
        return false;
      }
      let obj = this.userList.find(item => {
        return item.id === eventId;
      });
      this.saveForm.method = eventId;
      this.saveForm.methodName = obj.name;
    },

    onFormSelectedUser(eventId) {
      if (!eventId) {
        this.saveForm.userId = '';
        this.saveForm.userName = '';
        return false;
      }
      let obj = this.userList.find(item => {
        return item.id === eventId;
      });
      this.saveForm.userId = eventId;
      this.saveForm.userName = obj.name;
    },

    // 复制单元格 公共方法
    handleCopy(obj) {
      this.$copyText(obj).then(
          function () {
            Message.success("复制成功！");
          },
          function () {
            Message.error("复制失败，请手动复制！");
          }
      );
    },
  },

}
</script>

<style scoped>
  .formItem {
    width: 800px;
  }

</style>